<!-- src/views/pages/MaterialOutboundManage.vue -->
<template>
  <div class="material-outbound-manage">
    <!-- 顶栏 -->
    <TopBar />

    <!-- 内容区域 -->
    <div class="content">
      <!-- 菜单 -->
      <MenuLine />

      <!-- 操作栏 -->
      <div class="operation-bar">
        <el-button type="primary" @click="openAddDialog">添加出库记录</el-button>
      </div>

      <!-- 出库记录列表 -->
      <el-table :data="outboundList" style="width: 100%" border v-loading="loading">
        <el-table-column prop="id" label="ID" width="100" />
        <el-table-column prop="outboundNumber" label="出库编号" width="150" />
        <el-table-column prop="materialName" label="物资名称" />
        <el-table-column prop="quantity" label="数量" width="120" />
        <el-table-column prop="status" label="状态" width="120" />
        <el-table-column prop="operatorName" label="操作人" width="150" />
        <el-table-column prop="outboundTime" label="出库时间" width="250" />
        <el-table-column label="操作" width="300">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="openEditDialog(row)">编辑</el-button>
            <el-button type="danger" size="small" @click="deleteOutbound(row.id)">删除</el-button>
            <el-button type="success" size="small" @click="openReviewDialog(row)"
              :disabled="!isPendingStatus(row.status)">
              审核
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 添加/编辑弹窗 -->
      <el-dialog :title="dialogTitle" v-model="dialogVisible" width="30%" @close="resetForm">
        <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
          <el-form-item v-for="field in outboundFields" :key="field.key" :label="field.label" :prop="field.key">
            <el-input v-if="field.type === 'text'" v-model="form[field.key]" :placeholder="field.placeholder"
              :maxlength="field.maxLength" />
            <el-input v-if="field.type === 'number'" v-model.number="form[field.key]" type="number"
              :placeholder="field.placeholder" :min="1" />
            <el-select v-else-if="field.type === 'select'" v-model.number="form[field.key]"
              :placeholder="field.placeholder" style="width: 100%" :disabled="!field.options || !field.options.length"
              @change="handleSelectChange(field.key, $event)">
              <el-option v-for="option in field.options" :key="option.value" :label="option.label"
                :value="option.value" />
              <el-option v-if="!field.options || !field.options.length" disabled label="无可用选项" :value="0" />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm"
            :disabled="!materialOptions.length || !userOptions.length">确定</el-button>
        </template>
      </el-dialog>

      <!-- 审核弹窗 -->
      <el-dialog title="审核出库记录" v-model="reviewDialogVisible" width="30%" @close="resetReviewForm">
        <el-form :model="reviewForm" :rules="reviewRules" ref="reviewFormRef" label-width="80px">
          <el-form-item label="状态" prop="status">
            <el-select v-model="reviewForm.status" placeholder="请选择审核状态" style="width: 100%">
              <el-option label="通过" value="通过" />
              <el-option label="拒绝" value="拒绝" />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="reviewDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitReview">确定</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus';
import { useMaterialOutboundStore, outboundFields, type MaterialOutbound } from '@/stores/outbound';
import { useMaterialStore } from '@/stores/material';
import { useUserStore } from '@/stores/user';
import TopBar from '@/components/TopBar.vue';
import MenuLine from '@/components/MenuLine.vue';

// 出库、物资和用户 store
const outboundStore = useMaterialOutboundStore();
const materialStore = useMaterialStore();
const userStore = useUserStore();
const outboundList = ref<MaterialOutbound[]>([]);
const loading = ref(false);

// 物资和用户选项
const materialOptions = ref<{ value: number; label: string }[]>([]);
const userOptions = ref<{ value: number; label: string }[]>([]);

// 判断状态是否为“待审核”
const isPendingStatus = (status: string) => {
  const isPending = status === '待审核' || status === 'PENDING';
  console.log('状态检查:', status, 'isPending:', isPending);
  return isPending;
};

// 动态更新 outboundFields 的选项
const materialField = outboundFields.find(f => f.key === 'materialId');
const operatorField = outboundFields.find(f => f.key === 'operatorId');
if (materialField) materialField.options = materialOptions.value;
if (operatorField) operatorField.options = userOptions.value;

// 弹窗控制
const dialogVisible = ref(false);
const dialogTitle = ref('添加出库记录');
const isEdit = ref(false);
const form = ref<MaterialOutbound>({
  id: 0,
  outboundNumber: '',
  materialId: 0,
  materialName: '',
  quantity: 0,
  status: '待审核',
  operatorId: 0,
  operatorName: '',
  reviewerId: null,
  outboundTime: '',
  createTime: '',
});
const formRef = ref<FormInstance>();

// 审核弹窗
const reviewDialogVisible = ref(false);
const reviewForm = ref({
  id: 0,
  status: '',
  reviewerId: userStore.user?.id || 0,
});
const reviewFormRef = ref<FormInstance>();
const reviewRules = ref<FormRules>({
  status: [{ required: true, message: '请选择审核状态', trigger: 'change' }],
});

// 表单校验规则
const rules = ref<FormRules>({
  outboundNumber: [
    { required: true, message: '请输入出库编号', trigger: 'blur' },
    { pattern: /^OUT\d{3}$/, message: '出库编号格式为 OUT+3位数字（如 OUT001）', trigger: 'blur' },
  ],
  materialId: [
    { required: true, message: '请选择物资', trigger: 'change' },
    { type: 'number', min: 1, message: '请选择有效的物资', trigger: 'change' },
  ],
  quantity: [
    { required: true, message: '请输入数量', trigger: 'blur' },
    { type: 'number', min: 1, message: '数量必须大于0', trigger: 'blur' },
  ],
  operatorId: [
    { required: true, message: '请选择操作人', trigger: 'change' },
    { type: 'number', min: 1, message: '请选择有效的操作人', trigger: 'change' },
  ],
});

// 获取物资选项
const fetchMaterials = async () => {
  try {
    const materials = await materialStore.fetchMaterials();
    materialOptions.value = materials.map(material => ({
      value: material.id,
      label: material.name,
    }));
    const materialField = outboundFields.find(f => f.key === 'materialId');
    if (materialField) materialField.options = materialOptions.value;
    console.log('物资选项:', materialOptions.value);
  } catch (error) {
    ElMessage.error('获取物资列表失败');
    console.error('物资加载失败:', error);
  }
};

// 获取用户选项
const fetchUsers = async () => {
  try {
    const users = await userStore.fetchUsers();
    userOptions.value = users.map(user => ({
      value: user.id,
      label: user.realName,
    }));
    const operatorField = outboundFields.find(f => f.key === 'operatorId');
    if (operatorField) operatorField.options = userOptions.value;
    console.log('用户选项:', userOptions.value);
  } catch (error) {
    ElMessage.error('获取用户列表失败');
    console.error('用户加载失败:', error);
  }
};

// 获取出库记录列表
const fetchOutbounds = async () => {
  loading.value = true;
  try {
    const result = await outboundStore.fetchOutbounds();
    console.log('后端出库记录:', result);
    outboundList.value = result.map(outbound => {
      const materialName = materialOptions.value.find(opt => opt.value === outbound.materialId)?.label || '未知物资';
      const operatorName = userOptions.value.find(opt => opt.value === outbound.operatorId)?.label || '未知用户';
      const status = outbound.status === 'PENDING' ? '待审核' : outbound.status === 'APPROVED' ? '通过' : outbound.status === 'REJECTED' ? '拒绝' : outbound.status;
      return {
        ...outbound,
        status,
        materialName,
        operatorName,
        outboundTime: outbound.outboundTime ? new Date(outbound.outboundTime).toLocaleString() : '',
        createTime: outbound.createTime ? new Date(outbound.createTime).toLocaleString() : '',
      };
    });
    console.log('出库记录列表:', outboundList.value);
  } catch (error: any) {
    const errorMessage = error.response?.data?.message || '获取出库记录列表失败';
    ElMessage.error(errorMessage);
    console.error('出库记录加载失败:', error, error.response?.data);
  } finally {
    loading.value = false;
  }
};

// 处理选择变化（更新名称字段）
const handleSelectChange = (key: string, value: number) => {
  console.log(`选择变化: ${key} = ${value}, type: ${typeof value}`);
  if (key === 'materialId') {
    form.value.materialName = materialOptions.value.find(opt => opt.value === value)?.label || '';
    form.value.materialId = value;
  } else if (key === 'operatorId') {
    form.value.operatorName = userOptions.value.find(opt => opt.value === value)?.label || '';
    form.value.operatorId = value;
  }
};

// 打开添加弹窗
const openAddDialog = async () => {
  isEdit.value = false;
  dialogTitle.value = '添加出库记录';
  await Promise.all([fetchMaterials(), fetchUsers()]);
  if (!materialOptions.value.length || !userOptions.value.length) {
    ElMessage.error('无法加载物资或用户选项，请稍后重试');
    return;
  }
  form.value = {
    id: 0,
    outboundNumber: '',
    materialId: materialOptions.value[0]?.value || 0,
    materialName: materialOptions.value[0]?.label || '',
    quantity: 0,
    status: '待审核',
    operatorId: userStore.user?.id || userOptions.value[0]?.value || 0,
    operatorName: userStore.user?.realName || userOptions.value[0]?.label || '',
    reviewerId: null,
    outboundTime: '',
    createTime: '',
  };
  console.log('打开添加弹窗, 表单初始值:', form.value);
  dialogVisible.value = true;
};

// 打开编辑弹窗
const openEditDialog = async (row: MaterialOutbound) => {
  isEdit.value = true;
  dialogTitle.value = '编辑出库记录';
  await Promise.all([fetchMaterials(), fetchUsers()]);
  if (!materialOptions.value.length || !userOptions.value.length) {
    ElMessage.error('无法加载物资或用户选项，请稍后重试');
    return;
  }
  form.value = {
    ...row,
    materialId: row.materialId,
    operatorId: row.operatorId,
    createTime: row.createTime || '',
  };
  console.log('打开编辑弹窗, 表单初始值:', form.value);
  dialogVisible.value = true;
};

// 打开审核弹窗
const openReviewDialog = (row: MaterialOutbound) => {
  reviewForm.value = {
    id: row.id,
    status: '',
    reviewerId: userStore.user?.id || 0,
  };
  console.log('打开审核弹窗:', reviewForm.value);
  reviewDialogVisible.value = true;
};

// 提交表单（添加或编辑）
const submitForm = async () => {
  if (!formRef.value) return;
  console.log('提交前表单值:', form.value);
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const payload = {
          id: form.value.id,
          outboundNumber: form.value.outboundNumber,
          materialId: form.value.materialId,
          quantity: form.value.quantity,
          operatorId: form.value.operatorId,
        };
        console.log('提交出库记录:', payload);
        if (isEdit.value) {
          await outboundStore.updateOutbound(payload);
          ElMessage.success('编辑出库记录成功');
        } else {
          await outboundStore.createOutbound(payload);
          ElMessage.success('添加出库记录成功');
        }
        dialogVisible.value = false;
        await fetchOutbounds();
      } catch (error: any) {
        const errorMessage = error.response?.data?.message || (isEdit.value ? '编辑出库记录失败' : '添加出库记录失败');
        ElMessage.error(errorMessage);
        console.error('提交失败:', error, error.response?.data);
      }
    } else {
      console.log('表单校验失败:', form.value);
      ElMessage.error('请检查输入的出库编号、物资、数量或操作人');
    }
  });
};

// 提交审核
const submitReview = async () => {
  if (!reviewFormRef.value) return;
  reviewFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        console.log('提交审核:', reviewForm.value);
        await outboundStore.reviewOutbound(reviewForm.value);
        ElMessage.success('审核出库记录成功');
        reviewDialogVisible.value = false;
        await fetchOutbounds();
      } catch (error: any) {
        const errorMessage = error.response?.data?.message || '审核出库记录失败';
        ElMessage.error(errorMessage);
        console.error('审核失败:', error, error.response?.data);
      }
    }
  });
};

// 删除出库记录
const deleteOutbound = async (id: number) => {
  ElMessageBox.confirm('确定删除该出库记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        await outboundStore.deleteOutbound(id);
        ElMessage.success('删除出库记录成功');
        await fetchOutbounds();
      } catch (error: any) {
        const errorMessage = error.response?.data?.message || '删除出库记录失败';
        ElMessage.error(errorMessage);
        console.error('删除失败:', error, error.response?.data);
      }
    })
    .catch(() => {
      ElMessage.info('取消删除');
    });
};

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  form.value = {
    id: 0,
    outboundNumber: '',
    materialId: 0,
    materialName: '',
    quantity: 0,
    status: '待审核',
    operatorId: 0,
    operatorName: '',
    reviewerId: null,
    outboundTime: '',
    createTime: '',
  };
  console.log('重置表单:', form.value);
};

// 重置审核表单
const resetReviewForm = () => {
  if (reviewFormRef.value) {
    reviewFormRef.value.resetFields();
  }
  reviewForm.value = { id: 0, status: '', reviewerId: userStore.user?.id || 0 };
};

// 初始化加载
onMounted(async () => {
  console.log('初始化用户:', userStore.user);
  try {
    await Promise.all([fetchMaterials(), fetchUsers()]);
    await fetchOutbounds();
  } catch (error) {
    console.error('初始化加载失败:', error);
    ElMessage.error('页面初始化失败，请刷新重试');
  }
});
</script>

<style scoped>
.material-outbound-manage {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.content {
  padding-top: 60px;
  width: 80%;
  margin: 0 auto;
  padding-bottom: 60px;
}

.operation-bar {
  margin: 20px 0;
}

.el-table {
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
</style>